#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <sys/socket.h>
#include <sys/types.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define DEFAULT 28921

class UdpServer{
    private:
        int port;   // 端口号
        int sockfd;  //套接字
       // std::string ip;
    public:
        UdpServer(/*std::string _ip,*/ int _port = DEFAULT)
            :port(_port),
            sockfd(-1)
          /*  ip(_ip)*/
            {} 
        // 初始化
        bool InitServer(){
            // 创建套接字
            sockfd = socket(AF_INET, SOCK_DGRAM, 0); // IPV4, udp套接字, 默认协议
                if(sockfd < 0){  // 创建失败
                   std::cerr << "socket error" << std::endl;
                    return false;
                }
            std::cout << "socket creat success, fd is:" << sockfd << std::endl;  //文件描述符 3
            //绑定(套接字, )
            struct sockaddr_in local;
            memset(&local,'\0', sizeof(local));  //清空
            local.sin_family = AF_INET;
            local.sin_port = htons(port);  //绑定端口(设置网络序列)
          //  local.sin_addr.s_addr = inet_addr(ip.c_str()); // ip(点分十进制字符串转为整形)
          //
            local.sin_addr.s_addr = INADDR_ANY;  // 0

            if(bind(sockfd, (struct sockaddr*)&local, sizeof(local)) < 0){
                std::cerr << "bind error" << std::endl;
            }
            std::cout << "bind success" << std::endl;
            return true;
        }
        
        //启动
        void Start(){
            while(1){
                char buffer[128] = {0};
                struct sockaddr_in peer;   //远端发送信息
                socklen_t len = sizeof(peer);
                ssize_t size = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);//收数据
                if(size > 0){
                    buffer[size] = '\0';
                    int _port = ntohs(peer.sin_port);
                    std::string _ip = inet_ntoa(peer.sin_addr); //(将整形转回字符串)
                    std::cout <<  _ip << ":" << _port << "# " << buffer << std::endl;
                    // 回消息
                    std::string echo_msg = "server Get:--";
                    echo_msg += buffer;

                    sendto(sockfd, echo_msg.c_str(), echo_msg.size(), 0, (struct sockaddr*)&peer, len);
                }else{
                    std::cerr << "recvtrom error" << std::endl;
                }
              //  sendto();   //发数据
            }
        }
        ~UdpServer(){
            if(sockfd >= 0)
                close(sockfd);
        }

};        
